package sns.action;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.util.ServletContextAware;
import org.springframework.transaction.annotation.Transactional;

import sns.bean.User;
import sns.dao.UserDao;
import sns.service.UserService;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class UploadAction extends ActionSupport implements ServletContextAware{

	// injection
	private UserService userService;
	private UserDao userDao;
	// pass in
	private String fileFileName;
	private File file;

	// return
	
	//parameter
	ServletContext context;

	@Transactional
	public String execute()  throws IOException  {

		String path = context.getRealPath("img/avatar");
		System.out.println("Path is " + path);
		System.out.println("@@@@@@@@@@@@@@@@@@@@@@@ "+ fileFileName);
		User currentUser = userService.getCurrentUser();
		fileFileName = ""+currentUser.getIduser()+fileFileName.substring(fileFileName.lastIndexOf('.'));
		File target = new File(path, fileFileName);
		FileUtils.copyFile(file, target);
		
		currentUser.setAvatar(fileFileName);
		userDao.merge(currentUser);

		return ActionSupport.SUCCESS;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}


	@Override
	public void setServletContext(ServletContext context) {
		this.context= context;
		
	}
}
